/*
 * enian-admin框架核心js
 * enianAdmin.js
 * 
 */
(function() {
	
	var lister_pond={}; //监听池
	var module={loaded:[],i:0,c:0,done:null}; //监听池
	//var module_loaded;
	var enianAdmin = function() {
		return new enianAdmin.prototype.init();
	}

	enianAdmin.rootPath='';
	enianAdmin.prototype = {
		//定义一些静态变量
		// 构造函数方法
		'init': function() {
			//定义一些变量属性
			//document.write("<script language=javascript src='/static/s_app/jquery.js'></script>");
		},
	}

	//跳转指定页面
	enianAdmin.go = function(url, data, modth) {
		var modth = modth || 'get';
		if(modth==true){
			modth = 'post'
		}
		_call('go',{url, data, modth})
	}
	
	//版本信息
	enianAdmin.v = function() {
		return '0.1.20190113';
	}
	
	//扩展（自定义）内容
	enianAdmin.extend = function(name,obj) {
		var obj = obj || {};
		_call(name,obj)
	}
	
	//刷新页面
	enianAdmin.reload = function(url, data, modth) {
		var modth = modth || 'get';
		if(modth==true){
			modth = 'post';
		}
		_call('reload',{url, data, modth})
	}
	
	//渲染状态栏
	enianAdmin.render_nav_bar = function(obj) {
		_call('render_nav_bar',obj);
	}
	
	//获得地址
	//url 为空的时候自动获取当前页面
	//enianAdmin.url(url).param
	enianAdmin.url = function(href) {
		var href = href || window.location.href;
		return parseURL(href);
		function parseURL(url) {  
			 var a =  document.createElement('a');  
			 a.href = url;  
			 return{  
				 source: url,  
				 protocol: a.protocol.replace(':',''),  
				 host: a.hostname,  
				 port: a.port,  
				 query: a.search,  
				 params: (function(){  
				     var ret = {},  
				         seg = a.search.replace(/^\?/,'').split('&'),  
				         len = seg.length, i = 0, s;  
				     for (;i<len;i++) {  
				         if (!seg[i]) { continue; }  
				         s = seg[i].split('=');  
				         ret[s[0]] = decodeURI(s[1]);  
				     }  
				     return ret;  
				 })(),  
				 file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],  
				 hash: a.hash.replace('#',''),  
				 path: a.pathname.replace(/^([^\/])/,'/$1'),  
				 relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],  
				 segments: a.pathname.replace(/^\//,'').split('/')  
			 };
		}    

	}
	
	//监听各种事件enianAdmin.listen('on',function)
	enianAdmin.listen = function(type,callback){
		var type = type || 'all';
		if(type){
			lister_pond[type]=callback;
		}
	}
	
	//name 模块名称，js_module 加载的js文件，支持arr和str，模块内容
	enianAdmin.module = function(js_module,func){
		//加载js文件（模块）
		loadModule(js_module);
		module.i++;
		typeof func === 'function' && func(function(name, obj){
			// console.log('定义模块')
			//module_pond[name]=obj;
			enianAdmin[name]=obj
		})
		// console.log("总数：",module.c,module.i)
		if(module.i==module.c){
			module.done()
		}
		
	}
	
	enianAdmin.use = function(js_module,callback){
		//加载js文件（模块）
		loadModule(js_module);
		module.done=callback;
	}
	
	//加载模块，支持数组
	function loadModule(js_module){
		if(typeof js_module === 'object' && !isNaN(js_module.length)){
			module.c+=js_module.length;
			for(var i = 0; i< js_module.length; i++){
				if(enianAdmin.inArray(js_module[i],module.loaded)){
					module.c--
				}else{
					enianAdmin.loadJS(js_module[i])
					module.loaded.push(js_module[i])
					// console.log("加载模块：",js_module[i])
				}
			}
		}else{
			if(js_module){
				module.c++
				if(enianAdmin.inArray(js_module,module.loaded)){
					module.c--
				}else{
					enianAdmin.loadJS(js_module);
					module.loaded.push(js_module);
					// console.log("加载模块：",js_module)
				}
			
			}
		}
	}
	
	enianAdmin.inArray = function(search,arr){
		for (var i = 0; i < arr.length; i++) {
			if(arr[i] == search)return true;
		}
		return false;
	}
	
	//动态加载js
	enianAdmin.loadJS=function(url, callback){
	    var script = document.createElement('script'),
	        fn = callback || function(){};
	    	script.type = 'text/javascript';
	    //IE
	    if(script.readyState){
	        script.onreadystatechange = function(){
	            if( script.readyState == 'loaded' || script.readyState == 'complete' ){
	                script.onreadystatechange = null;
	                fn();
	            }
	        };
	    }else{
	        //其他浏览器
	        script.onload = function(){
	            fn();
	        };
	    }
	    script.src = url;
	    document.getElementsByTagName('head')[0].appendChild(script);
	}
	
	//开始 - 一般在主页运行
	enianAdmin.start=function(obj){
		var v = obj.v ? obj.v : new Date().getTime();
		if(obj.root){
			enianAdmin.rootPath=obj.root;
		}else{
			var configPath = document.scripts;
			enianAdmin.rootPath = configPath[configPath.length - 1].src.substring(0, configPath[configPath.length - 1].src.lastIndexOf("/") + 1);
		}
	   	enianAdmin.loadJS(enianAdmin.rootPath+'config.js?v='+v,function(){
	   		if(obj.done){
	   			obj.done();
	   		}
	   	});
	}
	
	function _call(name,obj){
		if(!lister_pond[name] && !lister_pond['all']){
			console.error('enianAdmin:不存在监听"'+name+'"的方法，因此该方法无效，可以使用.listen("'+name+'",function) 或 .listen("all",function) 来监听');
		}else{
			if(lister_pond[name]){
				lister_pond[name](obj);
			}else{
				obj.type=name;
				lister_pond['all'](obj);
			}
		}
	}
	
	enianAdmin.prototype.init.prototype = enianAdmin.prototype;
	window.admin = window.enianAdmin = enianAdmin; //对外开放	
	
})(window);
